import 'dart:convert';
import 'dart:math';
import 'dart:typed_data';

import 'package:flutter/widgets.dart';
import 'package:netease_cloud_music_api/netease_cloud_music_api.dart';
import 'package:netease_cloud_music_api/utils/hex.dart';
import 'package:netease_cloud_music_api/utils/player_request.dart';
import 'package:netease_cloud_music_api/utils/request.dart';
import 'package:shared_preferences/shared_preferences.dart';

mixin Song {
  /// 获取歌曲详情
  /// 说明 : 调用此接口 , 传入音乐 id, 可获得歌曲详情(注意:歌曲封面现在需要通过专辑内容接口获取)
  /// [ids] 音乐id 列表
  Future<PlayerRequestResponse> songDetail({required List<int> ids}) {
    Map<String, dynamic> data = {'ids': ids, 'c': ids.map((e) => "{'id': $e}").toList()};
    print(data);
    return PlayerRequest(
      url: 'https://music.163.com/weapi/v3/song/detail',
      data: data,
      options: PlayerRequestOptions(method: PlayerRequestMethod.post, crypto: EncryptType.weapi),
    ).request();
  }

  /// 调整歌单顺序
  /// 说明 : 登录后调用此接口,可以根据歌曲id顺序调整歌曲顺序
  /// [pid] 歌单id
  /// [ids] 歌曲id列表
  Future<PlayerRequestResponse> songOrderUpdate({required List<int> ids, required int pid}) {
    Map<String, dynamic> data = {'trackIds': ids, 'pid': pid, 'op': 'update'};
    return PlayerRequest(
      url: 'http://interface.music.163.com/api/playlist/manipulate/tracks',
      data: data,
      options: PlayerRequestOptions(method: PlayerRequestMethod.post, crypto: EncryptType.weapi, url: '/api/playlist/desc/update'),
    ).request();
  }

  Future<PlayerRequestResponse> songUrl({required List<int> ids, int br = 999000}) async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    String? getCookie = sharedPreferences.getString('cookie');
    Map<String, dynamic> storageCookie = getCookie == null ? Map<String, dynamic>() : json.decode(getCookie);
    String cookie = 'os=pc';
    if (!storageCookie.containsKey('MUSIC_U')) {
      Uint8List uint8list = Uint8List.fromList(List.generate(16, (index) => Random().nextInt(300)));
      cookie = '$cookie;${Hex.formatBytesAsHexString(uint8list)}';
    }
    Map<String, dynamic> data = {'ids': ids, 'br': br};
    return PlayerRequest(
      url: 'https://interface3.music.163.com/eapi/song/enhance/player/url',
      data: data,
      options: PlayerRequestOptions(
        method: PlayerRequestMethod.post,
        crypto: EncryptType.eapi,
        url: '/api/song/enhance/player/url',
        cookie: cookie,
      ),
    ).request();
  }
}
